package com.ls.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ls.blog.common.exception.BizException;
import com.ls.blog.dto.RoleDTO;
import com.ls.blog.entity.Role;
import com.ls.blog.entity.RoleResource;
import com.ls.blog.entity.UserRole;
import com.ls.blog.mapper.RoleMapper;
import com.ls.blog.service.RoleResourceService;
import com.ls.blog.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ls.blog.service.UserRoleService;
import com.ls.blog.utils.ObjectUtils;
import com.ls.blog.vo.RoleVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lishun
 * @since 2022-01-14
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    RoleMapper roleMapper;

    @Autowired
    RoleResourceService roleResourceService;

    @Autowired
    UserRoleService userRoleService;

    @Override
    public List<String> getRoleByUserId(Integer id) {
        return roleMapper.getRoleByUserId(id);
    }

    @Override
    public List<RoleDTO> listOpt() {
        List<Role> list = this.list();
        return ObjectUtils.copyList(list,RoleDTO.class);
    }

    @Override
    public List<RoleDTO> roleDTOList() {
        List<Role> roleList = this.list();
        return ObjectUtils.copyList(roleList,RoleDTO.class);
    }

    @Override
    public void editRole(RoleVO roleVO) {
        // 判断是否角色编码重复
        long count = this.count(new LambdaQueryWrapper<Role>().eq(Role::getName, roleVO.getName()));
        if (count>0){
            throw new BizException("角色唯一编码重复");
        }
        this.updateById(ObjectUtils.copyObject(roleVO,Role.class));
    }

    @Override
    public RoleDTO getRoleById(Integer id) {
        Role role = this.getById(id);
        return ObjectUtils.copyObject(role,RoleDTO.class);
    }

    @Override
    public void addRole(RoleVO roleVO) {
        // 判断是否角色编码重复
        long count = this.count(new LambdaQueryWrapper<Role>().eq(Role::getName, roleVO.getName()));
        if (count>0){
            throw new BizException("角色唯一编码重复");
        }
        this.save(ObjectUtils.copyObject(roleVO,Role.class));
    }

    @Override
    public void deleteRole(Integer id) {
        // Todo 可以建索引
        // 判断角色是否有用户
        long userCount = userRoleService.count(new LambdaQueryWrapper<UserRole>().eq(UserRole::getRid, id));
        if (userCount>0){
            throw new BizException("改角色下存在用户");
        }
        // 判断角色是否有资源
        long resourceCount = roleResourceService.count(new LambdaQueryWrapper<RoleResource>().eq(RoleResource::getRoleId, id));
        if (resourceCount>0){
            throw new BizException("改角色下存在资源");
        }
        // 可以删除
        this.removeById(id);
    }
}
